from sqlalchemy.orm import Session
from models.user import User
from typing import Optional
import hashlib

class UserDAO:
    @staticmethod
    def create_user(db: Session, username: str, password: str) -> Optional[User]:
        if UserDAO.get_user_by_username(db, username):
            return None  # 用户已存在
        hashed = UserDAO.hash_password(password)
        user = User(username=username, password_hash=hashed)
        db.add(user)
        db.commit()
        db.refresh(user)
        return user

    @staticmethod
    def get_user_by_username(db: Session, username: str) -> Optional[User]:
        return db.query(User).filter(User.username == username).first()

    @staticmethod
    def get_user_by_id(db: Session, user_id: int) -> Optional[User]:
        return db.query(User).filter(User.id == user_id).first()

    @staticmethod
    def verify_user_password(db: Session, username: str, password: str) -> bool:
        user = UserDAO.get_user_by_username(db, username)
        if not user:
            return False
        return user.password_hash == UserDAO.hash_password(password)

    @staticmethod
    def hash_password(password: str) -> str:
        return hashlib.sha256(password.encode("utf-8")).hexdigest()
